<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import UnitTreeDialog from "./unit-tree-dialog.vue";

const emit = defineEmits<{
  (e: "update:visible", val: boolean): void;
  (e: "update:unitId", val: string | undefined): void;
  (e: "update:unitName", val: string | undefined): void;
  (e: "change", ids: string, texts: string): void;
}>();

const props = defineProps({
  /**是否显示 */
  visible: {
    type: Boolean,
    default: false
  },
  unitId: {
    type: String
  },
  unitName: {
    type: String
  },
  multiple: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: "请选择部门"
  }
});

const unitTreeDialogRef = ref();

//设置是否显示双向绑定
const visibleModelValue = ref(props.visible);
watch(
  () => props.visible,
  val => {
    visibleModelValue.value = val;
  }
);
watch(visibleModelValue, val => {
  emit("update:visible", val);
});

//设置部门id双向绑定
const unitIdModelValue = ref(props.unitId);
watch(
  () => props.unitId,
  val => {
    unitIdModelValue.value = val;
  }
);
watch(unitIdModelValue, val => {
  emit("update:unitId", val);
});

//设置部门名称双向绑定
const unitNameModelValue = ref(props.unitName);
watch(
  () => props.unitName,
  val => {
    unitNameModelValue.value = val;
  }
);
watch(unitNameModelValue, val => {
  emit("update:unitName", val);
});

const UnitTreeDialogInputState = reactive({
  onSelectClick: () => {
    visibleModelValue.value = true;
  },
  onClearClick: () => {
    unitIdModelValue.value = undefined;
    unitNameModelValue.value = undefined;
  },
  onChangeUnit: (ids: string, texts: string) => {
    unitIdModelValue.value = ids;
    unitNameModelValue.value = texts;

    // if (Array.isArray(data)) {
    //   // 多选
    //   let unitNameStr = ''
    //   let unitIdStr = ''
    //   data.forEach(item => {
    //     unitNameStr += ',' + item.text
    //     unitIdStr += ',' + item.id
    //   })
    //   unitIdModelValue.value = unitIdStr.substring(1)
    //   unitNameModelValue.value = unitNameStr.substring(1)
    // } else {
    //   // 单选
    //   unitIdModelValue.value = data.id
    //   unitNameModelValue.value = data.text
    // }
    emit("change", ids, texts);
  }
});
</script>
<template>
  <unit-tree-dialog
    ref="unitTreeDialogRef"
    v-model:visible="visibleModelValue"
    :show-checkbox="multiple"
    @change-unit="UnitTreeDialogInputState.onChangeUnit"
  >
    <jxtech-select-input
      v-model:inputLabel="unitNameModelValue"
      v-model:inputValue="unitIdModelValue"
      :placeholder="placeholder"
      @select-click="UnitTreeDialogInputState.onSelectClick"
      @clear-click="UnitTreeDialogInputState.onClearClick"
    ></jxtech-select-input>
  </unit-tree-dialog>
</template>
